/**
 * 常用方法封装 请求，文件上传等
 * @author echo. 
 **/

const tui = {
	//接口地址
	interfaceUrl: function() {
		// #ifdef H5
		return ''
		// #endif
		// #ifdef APP-PLUS || MP-WEIXIN
		return 'https://a8gogo.com'
		// #endif
	},
	toast: function(text, duration, success) {
		uni.showToast({
			title: text || "出错啦~",
			icon: success ? 'success' : 'none',
			duration: duration || 2000
		})
	},
	modal: function(title, content, showCancel, callback, confirmColor, confirmText) {
		uni.showModal({
			title: title || '提示',
			content: content,
			showCancel: showCancel,
			cancelColor: "#999",
			confirmColor: confirmColor || "#3478f5",
			confirmText: confirmText || "确定",
			success(res) {
				if (res.confirm) {
					callback && callback(true)
				} else {
					callback && callback(false)
				}
			}
		})
	},
	//判断浏览器是否是微信浏览器
	checkIsWechatBrowser: function() {
		return (navigator.userAgent.toLowerCase().match(/MicroMessenger/i) == "micromessenger");
	},
	//微信浏览器中打开H5隐藏顶部导航方法
	hidePageNavInWechatBrowser: function() {
		//#ifdef H5
		if (tui.checkIsWechatBrowser()) {
			let pageNav = document.getElementsByTagName("uni-page-head");
			if (pageNav && pageNav[0]) {
				pageNav[0].style.display = "none";
			}
		}
		//#endif
	},
	isAndroid: function() {
		const res = uni.getSystemInfoSync();
		return res.platform.toLocaleLowerCase() == "android"
	},
	isPhoneX: function() {
		const res = uni.getSystemInfoSync();
		let iphonex = false;
		let models = ['iphonex', 'iphonexr', 'iphonexsmax', 'iphone11', 'iphone11pro', 'iphone11promax']
		const model = res.model.replace(/\s/g, "").toLowerCase()
		if (models.includes(model)) {
			iphonex = true;
		}
		return iphonex;
	},
	constNum: function() {
		let time = 0;
		// #ifdef APP-PLUS
		time = this.isAndroid() ? 300 : 0;
		// #endif
		return time
	},
	delayed: null,
	/**
	 * 请求数据处理
	 * @param string url 请求地址
	 * @param string method 请求方式
	 *  GET or POST
	 * @param {*} postData 请求参数
	 * @param bool isDelay 是否延迟显示loading
	 * @param bool isForm 数据格式
	 *  true: 'application/x-www-form-urlencoded'
	 *  false:'application/json'
	 * @param bool hideLoading 是否隐藏loading
	 *  true: 隐藏
	 *  false:显示
	 */
	request: function(url, method, postData, isDelay, isForm, hideLoading) {
		//接口请求
		let loadding = false;
		tui.delayed && uni.hideLoading();
		clearTimeout(tui.delayed);
		tui.delayed = null;
		// 加载
		// if (!hideLoading) {
		// 	tui.delayed = setTimeout(() => {
		// 		uni.showLoading({
		// 			mask: true,
		// 			title: '请稍候...',
		// 			success(res) {
		// 				loadding = true
		// 			}
		// 		})
		// 	}, isDelay ? 1000 : 0)
		// }
		// postData['token'] = tui.getToken();
		return new Promise((resolve, reject) => {
			uni.request({
				url: tui.interfaceUrl() + url,
				data: postData,
				header: {
					'content-type': isForm ? 'application/x-www-form-urlencoded' :
						'application/json',
					'token': tui.getToken()
				},
				method: method, //'GET','POST'
				dataType: 'json',
				success: (res) => {
					clearTimeout(tui.delayed)
					tui.delayed = null;
					if (loadding && !hideLoading) {
						uni.hideLoading();
					}
					if (res.data && res.data.code == 400) {
						// uni.clearStorageSync();
						uni.removeStorageSync('token');
						uni.removeStorageSync('user_id');
						uni.removeStorageSync('identity');
						tui.modal('提示', '登录信息已失效，请重新登录', false, () => {
							
							// app端进入方式
							// #ifdef  APP-PLUS
							uni.navigateTo({
								url: "/pages/login/thelogin"
							})
							// #endif
							// 小程序端进入方式
							// #ifdef MP-WEIXIN || H5
							uni.navigateTo({
								url: "/pages/login/thelogin"
							})
							// #endif
						})
						return false;
					}
					if (res.data && res.data.code == 401) {
						// uni.clearStorageSync();
						uni.removeStorageSync('token');
						uni.removeStorageSync('user_id');
						uni.removeStorageSync('identity');
						tui.modal('提示', res.data.msg, false, () => {
							// uni.navigateTo({
							// 	url: '/pages/authorize/authorize'
							// })
						})
						return false;
					}
					resolve(res.data)
				},
				fail: (res) => {
					clearTimeout(tui.delayed)
					tui.delayed = null;
					tui.toast("网络不给力，请稍后再试~")
					reject(res)
				}
			})
		})
	},
	/**
	 * 上传文件
	 * @param string url 请求地址
	 * @param string src 文件路径
	 */
	uploadFile: function(url, src) {
		console.log(1212);
		uni.showLoading({
			title: '请稍候...'
		})
		return new Promise((resolve, reject) => {
			const uploadTask = uni.uploadFile({
				url: tui.interfaceUrl() + url,
				filePath: src,
				name: 'file',
				header: {
					'Authorization': tui.getToken()
				},
				formData: {
					// sizeArrayText:""
				},
				success: function(res) {
					uni.hideLoading()
					let d = JSON.parse(res.data.replace(/\ufeff/g, "") || "{}")
					if (d.code == 1) {
						//返回图片地址
						let fileObj = d.data;
						resolve(fileObj)
					} else {
						tui.toast(res.msg);
					}
				},
				fail: function(res) {
					reject(res)
					tui.toast(res.msg);
				}
			})
		})
	},
	//获取token
	getToken() {
		return uni.getStorageSync("token");
	},
	// 计时器时分秒
	dateFormat(time) {
		let date = new Date(time);
		let year = date.getFullYear();
		// 在日期格式中，月份是从0开始的，因此要加0，使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
		let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
		let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
		let hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
		let minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
		let seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
		// 拼接
		// return year + "年" + month + "月" + day + "日" + hours + ":" + minutes + ":" + seconds;
		return hours + ":" + minutes + ":" + seconds;
		// return year + "-" + month + "-" + day;
	},
	// 获取当前时间年月日，时分秒
	dateTimeStr(str) {
		var date = new Date(),
			year = date.getFullYear(), //年
			month = date.getMonth() + 1, //月
			day = date.getDate(), //日
			hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(), //时
			minute = date.getMinutes() < 10 ? date.getMinutes() : date.getMinutes(), //分
			second = date.getSeconds() < 10 ? date.getSeconds() : date.getSeconds(); //秒
		month >= 1 && month <= 9 ? (month = "0" + month) : "";
		day >= 0 && day <= 9 ? (day = "0" + day) : "";
		hour >= 0 && hour <= 9 ? hour : "";
		minute >= 0 && minute <= 9 ? (minute = "0" + minute) : "";
		second >= 0 && second <= 9 ? (second = "0" + second) : "";
		if (str.indexOf('y') != -1) {
			str = str.replace('y', year)
		}
		if (str.indexOf('m') != -1) {
			str = str.replace('m', month)
		}
		if (str.indexOf('d') != -1) {
			str = str.replace('d', day)
		}
		if (str.indexOf('h') != -1) {
			str = str.replace('h', hour)
		}
		if (str.indexOf('i') != -1) {
			str = str.replace('i', minute)
		}
		if (str.indexOf('s') != -1) {
			str = str.replace('s', second)
		}
		return str;
	},
	getUserinfo: function() {
		return new Promise((resolve, reject) => {
			// #ifdef MP-WEIXIN || H5
			uni.getProvider({
				service: 'oauth',
				success: function(res) {
					if (~res.provider.indexOf('weixin')) {
						uni.login({
							provider: 'weixin',
							success: (res2) => {

								uni.getUserInfo({
									provider: 'weixin',
									success: (info) => { //这里请求接口
										info['code'] = res2['code'];
										resolve(info);

									},
									fail: () => {
										that.toast('微信登录授权失败');
									}
								})

							},
							fail: () => {
								that.toast('微信登录授权失败');
							}
						})

					} else {
						that.toast('请先安装微信或升级版本');
					}
				}
			});
			//#endif
		})

	},
	checkIsLogin() {
		// 如果token或者user_id任何一项为空就返回false
		return uni.getStorageSync("token") !== '' 
	},
	// 获取昨天和上一个月
	getMonthDay(monthnum, daynum) {
		// monthnum:几月前,daynum:几天前
		// console.log(monthnum,"月")
		let oneDay = 24 * 60 * 60 * 1000 * daynum
		let date = new Date(Date.now() - oneDay) // 昨天
		let nowDate = {
			year: date.getFullYear(), // 年
			month: date.getMonth() + 1, // 月份
			day: date.getDate(), // 当前日期前一天(昨天)
		}
		let startMonth = nowDate.month - monthnum
		let startYear = nowDate.year
		let startDay = nowDate.day
		if (startMonth <= 0) {
			startYear = startYear - 1
			startMonth = 12
		}
		let startLastDay = tui.getCurrentMonthLast(`${startYear}-${startMonth}`)
		if (nowDate.day > startLastDay) {
			startDay = startLastDay
		} else {
			startDay = nowDate.day
		}
		if(nowDate.day<=9){
			nowDate.day = "0"+nowDate.day
		}
		if(startMonth<=9){
			startMonth = "0"+startMonth
		}
		if (monthnum != "" && daynum != "") {
			return [
				// `${startYear}-${startMonth}-${startDay}`,
				`${startYear}-${startMonth}`,
				`${nowDate.year}-${nowDate.month}-${nowDate.day}`
			]
		}
		if (monthnum != "") {
			return `${startYear}-${startMonth}`
		}
		if (daynum != "") {
			return `${nowDate.year}-${nowDate.month}-${nowDate.day}`
		}
	},
	// 获取某月的最后一天 2021-2 -> 2021-2-28
	getCurrentMonthLast(date) {
		var endDate = new Date(date); //date 是需要传递的时间如：2018-08
		var month = endDate.getMonth();
		var nextMonth = ++month;
		var nextMonthFirstDay = new Date(endDate.getFullYear(), nextMonth, 1);
		var oneDay = 1000 * 60 * 60 * 24;
		var dateString = new Date(nextMonthFirstDay - oneDay);
		var dateArr = dateString.toLocaleDateString().split('/')
		return dateArr[dateArr.length - 1]; //toLocaleDateString() 返回 如：2018/8/31
	},
	doLogin: function() {
		tui.modal('登录提示', '去登陆', true, function(ret) {
			if (ret) {
				// app端进入方式
				// #ifdef  APP-PLUS || H5
				uni.navigateTo({
					url: "/pages/login/accountlogin"
				})
				// #endif
				// 小程序端进入方式
				// #ifdef MP-WEIXIN || H5
				uni.navigateTo({
					url: "/pages/login/accountlogin"
				})
				// #endif
			}

		});


	},
	saveHttpImg(url) {
		uni.showLoading({
			title: '保存中...'
		})
		uni.downloadFile({
			url: url, //仅为示例，并非真实的资源
			success: (res) => {
				if (res.statusCode === 200) {
					let file = res.tempFilePath;
					tui.save(file)
				} else {
					uni.hideLoading();
					tui.toast('保存失败');
				}
			}
		});
	},
	save(url) {
		let _this = this;
		uni.saveImageToPhotosAlbum({
			filePath: url,
			success: () => {
				uni.hideLoading();
				tui.toast('图片已保存');
			},
			fail: () => {
				uni.hideLoading();
				tui.toast('保存失败');
			},
			complete: () => {

			}
		});
	},
	chooseImage(num, type) {
		return new Promise((resolve, reject) => {
			uni.chooseImage({
				count: num,
				sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				sourceType: type, //从相册选择
				success: function(res) {
					resolve(res.tempFilePaths);
				}
			});
		})

	},
	/**
	 * @param {Object} user_type  使用端，1：小程序端，2：app端，3：pc端
	 * @param {Object} payment_type 支付类型，1：微信支付，2：支付宝支付，3：余额支付（直接支付逻辑）
	 * @param {Object} order_type #订单类型，1：普通商城 2 充值 3 押金
	 * @param {Object} order_id #订单id
	 */
	getPayInfo(user_type, payment_type, order_type, order_id) {

		return new Promise((resolve, reject) => {
			tui.request('api/pay/getPayInfo', 'POST', {
				user_type: user_type,
				payment_type: payment_type,
				order_type: order_type,
				order_id: order_id,
			}).then(res => {
				resolve(res);
			}).catch(err => {
				reject(err);
			});
		})

	},
	wechatAppPay(params) {
		return new Promise((resolve, reject) => {
			// params = JSON.parse(params);
			uni.requestPayment({
				"provider": "wxpay",
				"orderInfo": {
					"appid": params.appid, // 微信开放平台 - 应用 - AppId，注意和微信小程序、公众号 AppId 可能不一致
					"noncestr": params.noncestr, // 随机字符串
					"package": params.package, // 固定值
					"partnerid": params.partnerid, // 微信支付商户号
					"prepayid": params.prepayid, // 统一下单订单号 
					"timestamp": params.timestamp, // 时间戳（单位：秒）
					"sign": params.sign // 签名，这里用的 MD5 签名
				},
				success(res) {
					resolve(res);
				},
				fail(err) {
					resolve(err);
				}
			})
		})
	},
	wechatPay(params) {
		return new Promise((resolve, reject) => {
			uni.requestPayment({
				provider: 'wxpay',
				timeStamp: params.timeStamp,
				nonceStr: params.nonceStr,
				package: params.package,
				signType: params.signType,
				paySign: params.paySign,
				success: function(res) {
					resolve(res);
				},
				fail: function(err) {
					resolve(err);
				}
			});
		})

	},
	appLogin: function(platform, callback) {
		uni.getProvider({
			service: 'oauth',
			success: function(res) {
				//支持微信、qq和微博等
				if (platform == 'wxopen') {
					if (~res.provider.indexOf('weixin')) {
						uni.login({
							provider: 'weixin',
							onlyAuthorize: true,
							success: function(loginRes) {
								// console.log(loginRes);return false;
								callback({
									status: true,
									data: loginRes.code
								});
								// 获取用户信息
								// 	uni.getUserInfo({
								// 		provider: 'weixin',
								// 		success: function(infoRes) {
								// 			callback({
								// 				status: true,
								// 				data: infoRes.userInfo
								// 			});
								// 		},
								// 		fail() {
								// 			callback({
								// 				status: false,
								// 				data: {}
								// 			});
								// 		}
								// 	// });
							}
						});
					}
				}
				if (platform == 'qq') {
					//支持微信、qq和微博等
					if (~res.provider.indexOf('qq')) {
						uni.login({
							provider: 'qq',
							success: function(loginRes) {
								// 获取用户信息
								uni.getUserInfo({
									provider: 'qq',
									success: function(infoRes) {
										callback({
											status: true,
											data: infoRes.userInfo
										});
									},
									fail() {
										callback({
											status: false,
											data: {}
										});
									}
								});
							}
						});
					}
				}
			},
			fail() {
				callback({
					status: false,
					data: {}
				});
			}
		});
	},
	// 小程序保存图片
	savePosterPath(url) {
		uni.downloadFile({
			url: url,
			success: (resFile) => {
				if (resFile.statusCode === 200) {
					uni.getSetting({
						success: (res) => {

							if (!res.authSetting["scope.writePhotosAlbum"]) {

								uni.authorize({
									scope: "scope.writePhotosAlbum",
									success: () => {
										uni.saveImageToPhotosAlbum({
											filePath: resFile
												.tempFilePath,
											success: (res) => {
												uni.showToast({
													title: "保存成功！",
												});
											},
											fail: (res) => {
												uni.showToast({
													title: res
														.errMsg,
												});
											},
											complete: (res) => {},
										});
									},
									fail: () => {
										uni.showModal({
											title: "您已拒绝获取相册权限",
											content: "是否进入权限管理，调整授权？",
											success: (res) => {
												if (res.confirm) {
													uni.openSetting({
														success: (
															res
															) => {},
													});
												} else if (res
													.cancel) {
													uni.showToast({
														title: "已取消！",
													});
												}
											},
										});
									},
								});
							} else {
								uni.saveImageToPhotosAlbum({
									filePath: resFile.tempFilePath,
									success: (res) => {
										uni.showToast({
											title: "保存成功！",
										});
									},
									fail: (res) => {
										uni.showToast({
											title: '取消保存',
										});
									},
									complete: (res) => {},
								});
							}
						},
						fail: (res) => {


						},
					});
				} else {
					uni.showToast({
						title: resFile.errMsg,
					});
				}
			},
			fail: (res) => {

				uni.showToast({
					title: res.errMsg,
				});
			},
		});
	},

	/**
	 * scene解码
	 */
	scene_decode(e) {
		if (e === undefined)
			return {};
		let scene = decodeURIComponent(e),
			params = scene.split(','),
			data = {};
		for (let i in params) {
			var val = params[i].split(':');
			val.length > 0 && val[0] && (data[val[0]] = val[1] || null)
		}
		return data;
	},

	/**
	 * 获取场景值(scene)
	 */
	getSceneData(query) {
		return query.scene ? tui.scene_decode(query.scene) : {};
	},
	returnDate(timer) {
		var date = new Date(timer); //当前时间
		var year = date.getFullYear() //返回指定日期的年份
		var month = repair(date.getMonth() + 1); //月
		var day = repair(date.getDate()); //日
		var curTime = year + "-" + month + "-" + day
	
		function repair(i) {
			if (i >= 0 && i <= 9) {
				return "0" + i;
			} else {
				return i;
			}
		}
		return curTime
	},
	// 米，公里转换
	returnKmUnit(m) {
		var v;
		if (typeof m === 'number' && !isNaN(m)) {
			if (m >= 1000) {
				v = (m / 1000).toFixed(2) + 'km'
			} else {
				v = m + 'm'
			}
		} else {
			v = '0m'
		}
		return v;
	}



}

export default tui
module.exports = {
	getUserinfo: tui.getUserinfo,
	request: tui.request,
	toast: tui.toast,
	checkIsLogin: tui.checkIsLogin,
	doLogin: tui.doLogin,
	saveHttpImg: tui.saveHttpImg,
	chooseImage: tui.chooseImage,
	uploadFile: tui.uploadFile,
	dateTimeStr: tui.dateTimeStr,
	dateFormat: tui.dateFormat,
	getPayInfo: tui.getPayInfo,
	wechatPay: tui.wechatPay,
	modal: tui.modal,
	appLogin: tui.appLogin,
	wechatAppPay: tui.wechatAppPay,
	savePosterPath: tui.savePosterPath,
	getSceneData: tui.getSceneData,
	hidePageNavInWechatBrowser: tui.hidePageNavInWechatBrowser,
	getMonthDay: tui.getMonthDay,
	getCurrentMonthLast: tui.getCurrentMonthLast,
	returnDate:tui.returnDate,
	returnKmUnit:tui.returnKmUnit
};
